/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Yahtzee;

/**
 *
 * @author agreseth
 */
import java.net.*;
import java.io.*;
import javax.swing.*;

public class MultiServerThread extends Thread {
    
    private Socket socket = null;
    PrintWriter out;
    BufferedReader in;
    String inputLine, outputLine;
    int finalScore;
    int finalScoreStart;
    int finalScoreEnd;
    String scoreStart = "Final Score";
    String scoreEnd = "<end>";
    ServerGUI gui;
    MultiServer serv;

    public MultiServerThread(Socket funSocket, ServerGUI gu, MultiServer serv)
    {
        super("MultiServerThread");
        this.socket = funSocket;
        this.gui = gu;
        this.serv = serv;
    }

    public void run()
    {
        try
        {
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //insert the yahtzee protocol code after actually making it...

            String temp[] = serv.getList();
            int i = 0;
            while (temp[i] != null)
            {
                System.out.println("hello " + temp[i]);
                out.println(temp[i]);
                i++;
            }
            System.out.println(serv.getList());
            out.println(serv.getList());
            System.out.println("In the run method...");
            out.println(socket.getLocalAddress());
            
            String result = in.readLine();
            System.out.println(result);
            // set this up to grab something that signifies final score
            finalScoreStart = result.indexOf(scoreStart);
            System.out.println(finalScoreStart);
            finalScoreEnd = result.indexOf(scoreEnd);
            System.out.println(finalScoreEnd);
            // final score
            String score = result.substring(finalScoreStart+12, finalScoreEnd-1);
            System.out.println(score);
            finalScore = Integer.parseInt(score);
            this.gui.messagesTextArea.append(score+"\n");
            System.out.println(finalScore);
            out.println(finalScore);
            System.out.println(socket.getInetAddress().toString());
            serv.setIP(socket.getInetAddress().toString());
            
        }
        catch (IOException e)
        {
            
        }
    }
    // gets the finalscore
    public int getFinalScore()
    {
        return finalScore;
    }
    public void close()
    {
        try
        {
            in.close();
            out.close();
            socket.close();
        }
        catch (Exception e)
        {
            System.out.println("Awww man...closing didn't work!");
        }
    }


}